// pages/user_end/peixun/peixun.js
const app = getApp();
const request = require('../../../utils/request.js');
const url = require('../../../utils/url.js');
const cookie = require('../../../utils/cookie.js');

Page({

    /**
     * 页面的初始数据
     */
    data: {
		id:0,
		money:0,
        name:"",
		sex:"",
		age:0,
		phone:"",
		unid_name:"",
		address:"",
		zhiwui:"",
		exam_time:"",	
		zhicheng:"初级",
		pxarray:[],
		zcarray:['初级','中级','高级'
		],
        idcard_front_image: "",
        idcard_front_image_url: "/static/icon/icon_upload_id1.png",
		
		gw_front_image: "",
		gw_front_image_url: "/static/icon/icon_upload_id1.png",
		
		jx_front_image: "",
		jx_front_image_url: "/static/icon/icon_upload_id1.png",
		
        idcard_back_image: "",
        idcard_back_image_url: "/static/icon/icon_upload_id2.png",
        regionValue: '',
        serverType: "",
        serverTypeRange: [],
        categorylist: [],
        servicetaglist: [],
        taglist: [],
        tagIds: [],
        imgs: [],
        picList: [],
        imgss: [],
        picLists: [],
        token: "",
        deposit: '',
        agreement:true,
		index:0,
		email:''
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
		this.setData({
		  id:options.id,
		  money:options.money
		})
		this.gettraindetail();
    },
	
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
            
      

    },
	choseRegion(e) {
		 const value = e.detail.value;
		 const str = value.join(',');
		console.log(str);
	  this.setData({
	    region: str
	  })
	},
	gettraindetail:function(){
	  var that = this;
	  let param = {
	    scoure: 'wxapp',
	    id: that.data.id,
		 token: that.data.token
	  }
	 console.log('id:'+that.data.id);
	  wx.showNavigationBarLoading(); //在当前页面显示导航条加载动画
	  request.request(url.gettraindetail, param, url.REQUEST_METHOD_GET).then((res) => {
	    wx.hideNavigationBarLoading(); //在当前页面隐藏导航条加载动画
		  console.log(res.data.data)
	    if(res.data.code==1){
	      that.setData({
	        pxarray:res.data.data
	      })
		  that.data.exam_time = that.data.pxarray[0];
		  
	     }
	  })  							
	
	},
	  bindPickerChange: function(e) {
		  var that = this;
		  
	    this.setData({
	      index: e.detail.value
	    })
		that.data.exam_time = that.data.pxarray[e.detail.value];
		console.log('picker发送选择改变，携带值为', that.data.exam_time)
		
	  },
	  bindzcChange: function(e) {
	  		  var that = this;
	  		  
	    this.setData({
	      index: e.detail.value,
		  zhicheng: that.data.zcarray[e.detail.value]
	    })
	  		// that.data.zhicheng = that.data.zcarray[e.detail.value];
	  		console.log('picker发送选择改变，携带值为', that.data.zhicheng)
	  		
	  },
	changename(e) {
	    this.setData({
	        name: e.detail.value
	    })
	},
	changesex(e) {
	    this.setData({
	        sex: e.detail.value
	    })
	},
	changeage(e) {
	    this.setData({
	        age: e.detail.value
	    })
	},
	changephone(e) {
	    this.setData({
	        phone: e.detail.value
	    })
	},
	changeunid_name(e) {
	    this.setData({
	        unid_name: e.detail.value
	    })
	},
	changezhiwui(e) {
	    this.setData({
	        zhiwui: e.detail.value
	    })
	},
	changemoney(e) {
	    this.setData({
	        money: e.detail.value
	    })
	},
	changeorder_time(e) {
	    this.setData({
	        order_time: e.detail.value
	    })
	},
	changaddress(e) {
	    this.setData({
	        address: e.detail.value
	    })
	},
	changemail(e) {
	    this.setData({
	        email: e.detail.value
	    })
	},
	apply() {
		var that = this;
        if (!that.data.name) {
            wx.showToast({
                title: '请输入姓名',
                icon: 'none'
            })
            return false;
        }
        if (!that.data.phone) {
            wx.showToast({
                title: '请输入手机号码',
                icon: 'none'
            })
            return false;
        }
        let reg = /^1[0-9]{10}$/
        if (!reg.test(that.data.phone)) {
            wx.showToast({
                title: '请输入正确手机号码',
                icon: 'none'
            })
            return false;
        }
        if (!that.data.address) {
            wx.showToast({
                title: '请选择地址',
                icon: 'none'
            })
            return false;
        }
        if (!that.data.idcard_front_image) {
            wx.showToast({
                title: '请上传身份证正面照片',
                icon: 'none'
            })
            return false;
        }
        if (!that.data.idcard_back_image) {
            wx.showToast({
                title: '请上传身份证背面照片',
                icon: 'none'
            })
            return false;
        }

        let param = {
            scoure: 'wxapp',
			train_id:that.data.id,
            token: that.data.token,
            name: that.data.name,
            money: that.data.money,
            address: that.data.address,
			sex:that.data.sex,
			age:that.data.age,
			phone:that.data.phone,
            zhiwui: that.data.zhiwui,
			unid_name:that.data.unid_name,
			exam_time:that.data.exam_time,
            idcard_front_image: that.data.idcard_front_image,
            idcard_back_image: that.data.idcard_back_image,
			gw_front_image:that.data.gw_front_image,
			jx_front_image:that.data.jx_front_image,
			zhicheng:that.data.zhicheng,
			email:that.data.email,
			region:region
        }
		// console.log('==============');
		// console.log(param);
		
        wx.showNavigationBarLoading(); //在当前页面显示导航条加载动画
        request.request(url.warehousing, param, url.REQUEST_METHOD_POST).then((res) => {
            wx.hideNavigationBarLoading(); //在当前页面隐藏导航条加载动画
            wx.showToast({
                title: res.data.msg,
                icon: "none"
            });

            if (res.data.code == 1) {
                //直接支付成功
                var config = JSON.parse(res.data.data.wxconfig);
                console.log("获取成功", JSON.parse(res.data.data.wxconfig));
                wx.requestPayment({
                  'timeStamp': config.timestamp,
                  'nonceStr': config.nonceStr,
                  'package': config.package,
                  'signType': config.signType,
                  'paySign': config.paySign,
                  'success': function (res2) {
                    console.log("成功", res2)
                    if (res2.errMsg == 'requestPayment:ok') {
                      wx.showToast({
                        title: '支付成功',
                        icon: 'success'
                      })
               
                      setTimeout(function () {
                        wx.navigateBack({
                            delta: 2
                        })
                    }, 1500)

                      return false;
                    }
                  },
                  'fail': function (res2) {
                    that.goMine();
                    return false;
                  },
                  'complete': function (res2) {}
                })
              } else {
                wx.showToast({
                  title: res.data.msg,
                  icon: 'none',
                  duration: 2000
                })
              }
            })
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        var that = this;
        cookie.getCookie('userInfo', function (res) {
            if (res) {
                var etime = Date.parse(new Date()) / 1000;

                if (etime < res.expiretime) {
                    that.setData({
                        login: 1,
                        token: res.token
                    })
                }
            }
        })
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    changeAgreement(){
        this.setData({
            agreement:false
        })
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },
      showDatePicker: function() {
        wx.chooseDate({
          startDate: '2020-01-01', // 开始日期
          endDate: '2021-12-31', // 结束日期
          success: function(res) {
            var date = res.date;
            var year = date.getFullYear();
            var month = date.getMonth() + 1;
            var day = date.getDate();
            var formattedDate = year + '-' + month + '-' + day;
            that.setData({
              date: formattedDate
            });
          }
        });
      },
    // 删除图片
    deleteImg: function (e) {
        var imgs = this.data.imgs;
        var picList = this.data.picList;
        var index = e.currentTarget.dataset.index;
        imgs.splice(index, 1);
        picList.splice(index, 1);
        this.setData({
            imgs: imgs,
            picList: picList
        });
        console.log(picList);
    },
    chooseImg: function (e) {
        var that = this;
        var imgs = this.data.imgs;
        if (imgs.length >= 3) {
            this.setData({
                lenMore: 1
            });
            setTimeout(function () {
                that.setData({
                    lenMore: 0
                });
            }, 2500);
            return false;
        }
        var count = 3 - imgs.length;
        if (count < 1) {
            return false;
        }

        wx.chooseImage({
            count: count, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: function (res) {
                // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
                if (res.errMsg == "chooseImage:ok") {
                    wx.showLoading({ //显示loding提示框
                        title: '正在上传中...',
                    })
                    let picList = that.data.picList
                    var imgs = that.data.imgs;
                    res.tempFilePaths.forEach((item, index) => {
                        imgs.push(item)
                        that.setData({
                            imgs: imgs,
                        });
                        wx.uploadFile({
                            url: url.HttpServerHostAddress + url.uploadpic,
                            filePath: item,
                            name: 'file',
                            formData: {
                                token: that.data.token
                            },
                            success: function (res) {
                                let ress = JSON.parse(res.data)
                                if (ress.code == 1) {
                                    var picList = that.data.picList;
                                    picList.push(JSON.parse(res.data).data.url);
                                    that.setData({
                                        picList: picList,
                                    })
                                    console.log(picList);
                                } else {
                                    wx.showToast({
                                        title: JSON.parse(res.data).msg,
                                        icon: 'none',
                                        duration: 3000
                                    })
                                    return;
                                }
                            },
                            fail: res => {
                                console.log(res)
                            }
                        })
                    })
                    wx.hideLoading(); //隐藏loading提示框
                }
            }
        });
    },

    deleteImgs: function (e) {
        var imgs = this.data.imgss;
        var picList = this.data.picLists;
        var index = e.currentTarget.dataset.index;
        imgs.splice(index, 1);
        picList.splice(index, 1);
        this.setData({
            imgss: imgs,
            picLists: picList
        });
        console.log(picList);
    },
    chooseImgs: function (e) {
        var that = this;
        var imgs = this.data.imgss;
        if (imgs.length >= 4) {
            this.setData({
                lenMore: 1
            });
            setTimeout(function () {
                that.setData({
                    lenMore: 0
                });
            }, 2500);
            return false;
        }
        var count = 4 - imgs.length;
        if (count < 1) {
            return false;
        }

        wx.chooseImage({
            count: count, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: function (res) {
                // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
                if (res.errMsg == "chooseImage:ok") {
                    wx.showLoading({ //显示loding提示框
                        title: '正在上传中...',
                    })
                    let picList = that.data.picLists
                    var imgs = that.data.imgss;
                    res.tempFilePaths.forEach((item, index) => {
                        imgs.push(item)
                        that.setData({
                            imgss: imgs,
                        });
                        wx.uploadFile({
                            url: url.HttpServerHostAddress + url.uploadpic,
                            filePath: item,
                            name: 'file',
                            formData: {
                                token: that.data.token
                            },
                            success: function (res) {
                                let ress = JSON.parse(res.data)
                                if (ress.code == 1) {
                                    var picList = that.data.picLists;
                                    picList.push(JSON.parse(res.data).data.url);
                                    that.setData({
                                        picLists: picList,
                                    })
                                    console.log(picList);
                                } else {
                                    wx.showToast({
                                        title: JSON.parse(res.data).msg,
                                        icon: 'none',
                                        duration: 3000
                                    })
                                    return;
                                }
                            },
                            fail: res => {
                                console.log(res)
                            }
                        })
                    })
                    wx.hideLoading(); //隐藏loading提示框
                }
            }
        });
    },
    choseType(e) {
        var that = this;
        var id = e.currentTarget.dataset.id;
        that.data.categorylist.forEach((item, index) => {
            if (item.id == id) {
                if (item.active == 1) {
                    var active = 0;
                } else {
                    var active = 1;
                }
                var sItem = 'categorylist[' + index + '].active';
                that.setData({
                    [sItem]: active
                })
            }
        });
        var array = [];
        var arrayIds = [];
        that.data.categorylist.forEach((item, index) => {
            if (item.active == 1) {
                array.push(that.data.categorylist[index].name);
                arrayIds.push(that.data.categorylist[index].id);
            }
        })

        that.setData({
            serverType: array,
            sevice_category_id: arrayIds
        })
    },
    uploadidcardImage(e) {
        var type = e.currentTarget.dataset.type;
        var that = this;
        wx.chooseImage({
            count: 1, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: function (res) {
                // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
                if (res.errMsg == "chooseImage:ok") {
                    wx.showLoading({ //显示loding提示框
                        title: '正在上传中...',
                    })
                    res.tempFilePaths.forEach((item, index) => {

                        wx.uploadFile({
                            url: url.HttpServerHostAddress + url.uploadpic,
                            filePath: item,
                            name: 'file',
                            formData: {
                                token: that.data.token
                            },
                            success: function (res) {
                                let ress = JSON.parse(res.data)
                                if (ress.code == 1) {
                                    if (type == 1) {
                                        that.setData({
                                            uploadfront: 1,
                                            idcard_front_image: JSON.parse(res.data).data.url,
                                            idcard_front_image_url: JSON.parse(res.data).data.fullurl
                                        })
                                    } else {
                                        that.setData({
                                            uploadback: 1,
                                            idcard_back_image: JSON.parse(res.data).data.url,
                                            idcard_back_image_url: JSON.parse(res.data).data.fullurl
                                        })
                                    }
                                } else {
                                    wx.showToast({
                                        title: JSON.parse(res.data).msg,
                                        icon: 'none',
                                        duration: 3000
                                    })
                                    return;
                                }
                            },
                            fail: res => {
                                console.log(res)
                            }
                        })
                    })
                    wx.hideLoading(); //隐藏loading提示框
                }
            }
        });
        wx.chooseImages({
            count: 1, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: function (res) {
                // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
                if (res.errMsg == "chooseImage:ok") {
                    wx.showLoading({ //显示loding提示框
                        title: '正在上传中...',
                    })
                    res.tempFilePaths.forEach((item, index) => {

                        wx.uploadFile({
                            url: url.HttpServerHostAddress + url.uploadpic,
                            filePath: item,
                            name: 'file',
                            formData: {
                                token: that.data.token
                            },
                            success: function (res) {
                                let ress = JSON.parse(res.data)
                                if (ress.code == 1) {
                                    if (type == 1) {
                                        that.setData({
                                            uploadfront: 1,
                                            idcard_front_image: JSON.parse(res.data).data.url,
                                            idcard_front_image_url: JSON.parse(res.data).data.fullurl
                                        })
                                    } else {
                                        that.setData({
                                            uploadback: 1,
                                            idcard_back_image: JSON.parse(res.data).data.url,
                                            idcard_back_image_url: JSON.parse(res.data).data.fullurl
                                        })
                                    }
                                } else {
                                    wx.showToast({
                                        title: JSON.parse(res.data).msg,
                                        icon: 'none',
                                        duration: 3000
                                    })
                                    return;
                                }
                            },
                            fail: res => {
                                console.log(res)
                            }
                        })
                    })
                    wx.hideLoading(); //隐藏loading提示框
                }
            }
        });

    },
	uploadgwImage(e) {
	    var type = e.currentTarget.dataset.type;
	    var that = this;
	    wx.chooseImage({
	        count: 1, // 默认9
	        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
	        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
	        success: function (res) {
	            // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
	            if (res.errMsg == "chooseImage:ok") {
	                wx.showLoading({ //显示loding提示框
	                    title: '正在上传中...',
	                })
	                res.tempFilePaths.forEach((item, index) => {
	
	                    wx.uploadFile({
	                        url: url.HttpServerHostAddress + url.uploadpic,
	                        filePath: item,
	                        name: 'file',
	                        formData: {
	                            token: that.data.token
	                        },
	                        success: function (res) {
	                            let ress = JSON.parse(res.data)
	                            if (ress.code == 1) {
	                                if (type == 1) {
	                                    that.setData({
	                                        uploadfront: 1,
	                                        gw_front_image: JSON.parse(res.data).data.url,
	                                        gw_front_image_url: JSON.parse(res.data).data.fullurl
	                                    })
	                                } 
	                            } else {
	                                wx.showToast({
	                                    title: JSON.parse(res.data).msg,
	                                    icon: 'none',
	                                    duration: 3000
	                                })
	                                return;
	                            }
	                        },
	                        fail: res => {
	                            console.log(res)
	                        }
	                    })
	                })
	                wx.hideLoading(); //隐藏loading提示框
	            }
	        }
	    });
	    wx.chooseImages({
	        count: 1, // 默认9
	        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
	        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
	        success: function (res) {
	            // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
	            if (res.errMsg == "chooseImage:ok") {
	                wx.showLoading({ //显示loding提示框
	                    title: '正在上传中...',
	                })
	                res.tempFilePaths.forEach((item, index) => {
	
	                    wx.uploadFile({
	                        url: url.HttpServerHostAddress + url.uploadpic,
	                        filePath: item,
	                        name: 'file',
	                        formData: {
	                            token: that.data.token
	                        },
	                        success: function (res) {
	                            let ress = JSON.parse(res.data)
	                            if (ress.code == 1) {
	                                if (type == 1) {
	                                    that.setData({
	                                        uploadfront: 1,
	                                        idcard_front_image: JSON.parse(res.data).data.url,
	                                        idcard_front_image_url: JSON.parse(res.data).data.fullurl
	                                    })
	                                } else {
	                                    that.setData({
	                                        uploadback: 1,
	                                        idcard_back_image: JSON.parse(res.data).data.url,
	                                        idcard_back_image_url: JSON.parse(res.data).data.fullurl
	                                    })
	                                }
	                            } else {
	                                wx.showToast({
	                                    title: JSON.parse(res.data).msg,
	                                    icon: 'none',
	                                    duration: 3000
	                                })
	                                return;
	                            }
	                        },
	                        fail: res => {
	                            console.log(res)
	                        }
	                    })
	                })
	                wx.hideLoading(); //隐藏loading提示框
	            }
	        }
	    });
	
	},
	uploadjxImage(e) {
	    var type = e.currentTarget.dataset.type;
	    var that = this;
	    wx.chooseImage({
	        count: 1, // 默认9
	        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
	        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
	        success: function (res) {
	            // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
	            if (res.errMsg == "chooseImage:ok") {
	                wx.showLoading({ //显示loding提示框
	                    title: '正在上传中...',
	                })
	                res.tempFilePaths.forEach((item, index) => {
	
	                    wx.uploadFile({
	                        url: url.HttpServerHostAddress + url.uploadpic,
	                        filePath: item,
	                        name: 'file',
	                        formData: {
	                            token: that.data.token
	                        },
	                        success: function (res) {
	                            let ress = JSON.parse(res.data)
	                            if (ress.code == 1) {
	                                if (type == 1) {
	                                    that.setData({
	                                        uploadfront: 1,
	                                        jx_front_image: JSON.parse(res.data).data.url,
	                                        jx_front_image_url: JSON.parse(res.data).data.fullurl
	                                    })
	                                } 
	                            } else {
	                                wx.showToast({
	                                    title: JSON.parse(res.data).msg,
	                                    icon: 'none',
	                                    duration: 3000
	                                })
	                                return;
	                            }
	                        },
	                        fail: res => {
	                            console.log(res)
	                        }
	                    })
	                })
	                wx.hideLoading(); //隐藏loading提示框
	            }
	        }
	    });
	    wx.chooseImages({
	        count: 1, // 默认9
	        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
	        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
	        success: function (res) {
	            // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
	            if (res.errMsg == "chooseImage:ok") {
	                wx.showLoading({ //显示loding提示框
	                    title: '正在上传中...',
	                })
	                res.tempFilePaths.forEach((item, index) => {
	
	                    wx.uploadFile({
	                        url: url.HttpServerHostAddress + url.uploadpic,
	                        filePath: item,
	                        name: 'file',
	                        formData: {
	                            token: that.data.token
	                        },
	                        success: function (res) {
	                            let ress = JSON.parse(res.data)
	                            if (ress.code == 1) {
	                                if (type == 1) {
	                                    that.setData({
	                                        uploadfront: 1,
	                                        idcard_front_image: JSON.parse(res.data).data.url,
	                                        idcard_front_image_url: JSON.parse(res.data).data.fullurl
	                                    })
	                                } else {
	                                    that.setData({
	                                        uploadback: 1,
	                                        idcard_back_image: JSON.parse(res.data).data.url,
	                                        idcard_back_image_url: JSON.parse(res.data).data.fullurl
	                                    })
	                                }
	                            } else {
	                                wx.showToast({
	                                    title: JSON.parse(res.data).msg,
	                                    icon: 'none',
	                                    duration: 3000
	                                })
	                                return;
	                            }
	                        },
	                        fail: res => {
	                            console.log(res)
	                        }
	                    })
	                })
	                wx.hideLoading(); //隐藏loading提示框
	            }
	        }
	    });
	
	}
})